//在页面未加载完毕之前显示的loading Html自定义内容
var _LoadingHtml = '<div id="loadingDiv" style="display: none; "><div id="over" style=" position: absolute;top: 0;left: 0; width: 100%;height: 100%; background-color: #f5f5f5;opacity:0.5;z-index: 1000;"></div><div id="layout" style="position: absolute;top: 40%; left: 30%;width: 20%; height: 20%;  z-index: 1001;text-align:center;"><img src="img/loading.gif" /></div></div>';
//呈现loading效果
document.write(_LoadingHtml);

//移除loading效果
function completeLoading() {
    document.getElementById("loadingDiv").style.display="none";
}


//展示loading效果
function showLoading(i)
{
    i=i?i:3;
    document.getElementById("loadingDiv").style.display="block";
    setTimeout(()=>{completeLoading();  },i*1000);
}



mqttmsg={
//收到消息后获取cache里面的mqtt_content,group,chatbody
      showdate:null,
      client:null,
      group:{},
      mqtt_content:null,
      mqtt_key:"mqtt_content",
      fromId:null,
      memberId:undefined,
      topicStr:"xuanzhu_",
      connectUrl : 'ws://www.xuanzhu123.com:8083/mqtt',
      noteElem:[".index-top-newslist"], //提示消息
      serverTopic:"_00001",
      loadsize:20,
    rewrite:function (t){
          var d={};
          if(t)d.detail=t;
        var mqttnewchatsNotieEvent = new CustomEvent('mqttnewchatsNotie', d);
        if(window.dispatchEvent) {
            window.dispatchEvent(mqttnewchatsNotieEvent);
        } else {
            window.fireEvent(mqttnewchatsNotieEvent);
        }
    },
getnowTime(){
     return new Date();
},
getFormatTime(){
    return new Date().format("yyyy-MM-dd hh:mm:ss");
}    ,
getDate(){
    return mqttmsg.getnowTime().format("yyyy-MM-dd");
},
getTime(){
    return mqttmsg.getnowTime().format("hh:mm:ss");
},
getMytopicName(){
  return  mqttmsg.topicStr + mqttmsg.memberId;
},
gettopicName(){
    return  mqttmsg.topicStr + mqttmsg.fromId;
},
getGroupName(fromId){

          if(!fromId&&!mqttmsg.fromId)return null;
    return  (fromId?fromId:mqttmsg.fromId)+"_"+mqttmsg.memberId;
},
    //根据fromId,MemberId获取group,获取不到就创建一个
getGroup:  function (fromid,nowdate) {
   if(!mqttmsg.mqtt_content)   mqttmsg.mqtt_content={};
    if(mqttmsg.mqtt_content&&mqttmsg.getGroupName(fromid)){
        if(!mqttmsg.mqtt_content.groups){

            mqttmsg.mqtt_content.groups={};
            mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)]={newchats:[]};
          //  mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)][nowdate?nowdate:mqttmsg.getDate()]={chats:[]};
        }
        if(!mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)]){
            mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)]={newchats:[]};

        }
        if(! mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)][nowdate?nowdate:mqttmsg.getDate()]){
            mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)][nowdate?nowdate:mqttmsg.getDate()]={chats:[]};
        }
      //  console.log(mqttmsg.mqtt_content.groups);
        server.setchatnews(mqttmsg.mqtt_key ,JSON.stringify(mqttmsg.mqtt_content));
        return mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)][nowdate?nowdate:mqttmsg.getDate()];
    }else{
       // pop_up('获取消息队列失败');
        console.log('获取消息队列失败')
    }
},

//从cache获取chats
    getnewChats:function  (fromid) {
        mqttmsg.getGroup(fromid);
        if(!mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)]){
            mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)]={newchats:[]};
        }
    if(!mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)].newchats){
        mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)].newchats=[];
    }
    return mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)].newchats;
},
  getGroups:function  (fromid) {
      mqttmsg.getGroup(fromid);
     return mqttmsg.mqtt_content.groups[mqttmsg.getGroupName(fromid)];
  },
initMQTT:function (fromid) {
    //从session获取聊天记录
    mqttmsg.showdate=mqttmsg.getDate();
   //if(!mqttmsg.mqtt_content)
    try{
      let json=  server.getchatnews(mqttmsg.mqtt_key);
        mqttmsg.mqtt_content = json?JSON.parse(json):{};
    }catch (e) {
        mqttmsg.mqtt_content={};
    }
       mqttmsg.getGroup(fromid);
},


//页面加载完之后初始化mqtt对象
    initmsg:function () {
        //创建MQTT 	cache
      //  server.setchatnews(mqttmsg.mqtt_key,{});
        //从数据库读取数据，初始化mqtt_content
        //设置有新消息提醒

        console.log('index.html mqtt init...');
        server.getUserInfo(function (res) {
            console.log("user info..");
            console.log(res);
            mqttmsg.memberId = res.id;
            mqttmsg.headimgurl = res.headimgurl;
            mqttmsg.nickname = res.nickname;
            console.log('mytopicName=' + mqttmsg.getMytopicName());

            // 连接选项
            var options = {
                clean: true, // true: 清除会话, false: 保留会话
                connectTimeout: 400000, // 超时时间
                // 认证信息
                clientId: mqttmsg.getMytopicName(),
                username: 'guest',
                password: 'guest',
            }

            // 连接字符串, 通过协议指定使用的连接方式
            // ws 未加密 WebSocket 连接
            // wss 加密 WebSocket 连接
            // mqtt 未加密 TCP 连接
            // mqtts 加密 TCP 连接
            // wxs 微信小程序连接
            // alis 支付宝小程序连接
            //     var connectUrl = 'wss://localhost:8083'

            mqttmsg.client = mqtt.connect(mqttmsg.connectUrl, options);
            mqttmsg. client.subscribe(mqttmsg.getMytopicName() + '/#');
          //  mqttmsg. client.subscribe(mqttmsg.serverTopic+"/#");

            mqttmsg.  client.on('connect',()=>{
                console.log('连接成功  ' );
                mqttmsg.initMQTT();
                server.getUserInfo(function (res) {
                    mqttmsg.memberId = res.id;
                    mqttmsg.headimgurl = res.headimgurl;
                    mqttmsg.nickname = res.nickname;
                    mqttmsg.client.publish(mqttmsg.serverTopic , JSON.stringify({code:2,data: {memberId:mqttmsg.memberId,from:mqttmsg.getMytopicName()}}), 1, function(error) {
                        console.log(' 获取取服务器新消息' );
                    })
                });

                })
            mqttmsg. client.on('reconnect', function(error) {
                console.log('正在重连:', error);
            });
            mqttmsg.client.on('error', (error) => {
                console.log('连接失败:', error)
            });
            mqttmsg.client.on('message', (topic, message) => {
               console.log('收到消息：', topic, message.toString());

                //设置有新消息提醒
                //server.setCache("newsmessage",1);
            if(topic.indexOf(mqttmsg.serverTopic)!=-1){
                console.log('收到消息：服务信息' );
                return;
            }
                var jmessage;
                try{
                     jmessage = JSON.parse(message);
                     mqttmsg.initMQTT(jmessage.memberId);
                }catch (e) { return; }
                //{"code":3,"chats":[]}
                if(jmessage.code==3){
                    if(jmessage.chats&&jmessage.chats.length>0){
                        mqttmsg.loadservernewChats(jmessage);
                    }
                    return;
                }
                if(!jmessage)return;
                var chatinfo = {};
                chatinfo.nickname = jmessage.nickname;
                chatinfo.image = jmessage.image;
                chatinfo.stime = jmessage.stime;
                chatinfo.content = jmessage.content;
                chatinfo.party = "other";
                chatinfo.date=jmessage.date;
                chatinfo.fromId = jmessage.memberId;
                mqttmsg.getGroups(jmessage.memberId).newchats.push(chatinfo);
                server.setchatnews(mqttmsg.mqtt_key,JSON.stringify(mqttmsg.mqtt_content));

                mqttmsg.client.publish(mqttmsg.serverTopic , JSON.stringify({code:4,data: {memberId:mqttmsg.memberId,groupName:jmessage.memberId+"_"+mqttmsg.memberId}}), 1, function(error) {
                    console.log(' 更新已读新消息' );
                })

             mqttmsg.shownewCathsList();
                mqttmsg.rewrite(true);
            })
          //  mqttmsg.initMQTT();
              mqttmsg.shownewCathsList();
        })

    },
    loadservernewChats:function (json){
     console.log(json);
        for (const chat in json.chats) {
            var chatinfo = {};
            chatinfo.nickname = json.nickname;
            chatinfo.image = json.image;
            chatinfo.stime = json.chats[chat].stime;
            chatinfo.content =  json.chats[chat].content;
            chatinfo.party = "other";
            chatinfo.date=json.date;
            chatinfo.fromId =  json.chats[chat].memberId;
            console.log( mqttmsg.getGroups( json.chats[chat].memberId));
          //  mqttmsg.getGroups(chat.memberId).newchats.push(chatinfo);
            mqttmsg.getnewChats( json.chats[chat].memberId).push(chatinfo);
        }
        server.setchatnews(mqttmsg.mqtt_key,JSON.stringify(mqttmsg.mqtt_content));
        //先后顺序不能变，否则不会有消息提醒
        mqttmsg.shownewCathsList();
        mqttmsg.rewrite(true);
    },

    /**
     * 新页面初使化调取新消息
     * @param fromId
     */
    loadNewChats:function (fromId){
        mqttmsg.group={chats:[]};
        if(!mqttmsg.getGroups(fromId).newchats||mqttmsg.getGroups(fromId).newchats.length==0||mqttmsg.getGroups(fromId).newchats[0].date==mqttmsg.showdate) {
            mqttmsg.loadoldchats(fromId,mqttmsg.showdate);
        }else{
            mqttmsg.showdate=null;
        }
        mqttmsg.getGroups(fromId).newchats.forEach(function (e) {
            console.log(e.date>mqttmsg.showdate)
                if(!mqttmsg.showdate) mqttmsg.showdate=e.data;
                mqttmsg.getGroup(fromId, e.date).chats.push({content: e.content, fromId: e.fromId, stime: e.stime});
                mqttmsg.getGroup(fromId, e.date).fromnickname = e.nickname;
                mqttmsg.getGroup(fromId, e.date).fromimage = e.image;
                mqttmsg.getGroup(fromId, e.date).date = e.date;

                mqttmsg.group.fromnickname = e.nickname;
                mqttmsg.group.fromimage = e.image;
                mqttmsg.group.chats.push({
                    image: e.image,
                    content: e.content,
                    fromId: e.fromId,
                    stime: (e.date == mqttmsg.getDate() ? '' : e.date ) + " " + e.stime,
                    date: e.date
                });

        })
        mqttmsg.getGroups(fromId).newchats=[];
        server.setchatnews(mqttmsg.mqtt_key,JSON.stringify(mqttmsg.mqtt_content));
        mqttmsg.shownewCathsList();
        return mqttmsg.group.chats.length;
    },
    loadoldchats:function (fromId,date){
        console.log("loadData:"+date)
       var group=   mqttmsg.getGroup(fromId,date);
      //  console.log(group);
        var newlist=[];
       group.chats.forEach(function (e){
           var image;
           if(group.fromnickname)
              mqttmsg.group.fromnickname =group.fromnickname;
           if(group.fromimage) {
               mqttmsg.group.fromimage = group.fromimage;
               image=group.fromimage;
           }
           if(group.nickname)
               mqttmsg.group.nickname =group.nickname;
           if(group.image){
               mqttmsg.group.image = group.image;
               image=group.image;
           }
            var chat=   {  image: image,  content: e.content,  stime: ((group.date == mqttmsg.getDate() ? '' : group.date) + " " + e.stime),  date: group.date,  };
            if(e.memberId){
                chat.memberId=e.memberId;
                chat.image=group.image;
            }else{
                chat.fromId=e.fromId;
                chat.image=group.fromimage;
            }
           newlist.push(chat);
       })

        if(date==mqttmsg.getDate()){
            mqttmsg.group.chats=   mqttmsg.group.chats.concat(newlist);
        }else{
            mqttmsg.group.chats=   newlist.concat(mqttmsg.group.chats);
           // mqttmsg.group.chats=newlist;
           // console.log(  mqttmsg.group.chats.unshift(newlist));
        }

        mqttmsg.showdate=date;
        return  group.chats.length;
    },
    //加载旧数据
loadoldchats1:function (fromId,i){



    for (const k in mqttmsg.getGroups(fromId)) {
        if(k=="newchats")continue;
        if(k<mqttmsg.showdate){
            if(k&&k!=mqttmsg.showdate)
                mqttmsg.loadoldchats(fromId,k);
            break;
        }

    }

},

//提示新消息
shownewCathsList:function (){
 var newchatslist=[];
 var newssize=0;
  //  mqttmsg.getGroups();
  //  console.log(mqttmsg.mqtt_content.groups)
if(!mqttmsg.mqtt_content||!mqttmsg.mqtt_content.groups)return newchatslist;

    for (const g in mqttmsg.mqtt_content.groups) {
       let e=mqttmsg.mqtt_content.groups[g];
        if(e.newchats&&e.newchats.length>0){
            newchatslist.push(e);
            newssize=newssize+e.newchats.length;
        }
        //console.log()
    }
    console.log("提示新消息"+newssize  +"  :"+newchatslist  )
    mqttmsg.noteElem.forEach(function (e){
    //  console.log(e);
      //  console.log(newchatslist);
       // console.log(newssize);
        server.loadData(e,{newchatslist:newchatslist,newssize:newssize})
    })

}
}

mqttmsg.initmsg();